﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MyWebApp.Common.Helper
{
    public class MvcIpHelper
    {
        /// <summary>
        /// 获取request 访问地址
        /// </summary>
        /// <param name="rq"></param>
        /// <returns></returns>
        public static string GetUserHostAddress(HttpRequestBase rq)
        {
            return rq.UserHostAddress;
        }
        /// <summary>
        /// 获取代理原始地址
        /// </summary>
        /// <param name="rq"></param>
        /// <returns></returns>
        public static string GetXFFAddress(HttpRequestBase rq)
        {
            string myip = string.Empty;
            //LogHelper.printInfoLog("X-Forwarded-For info:" + rq.ServerVariables["HTTP_X_FORWARDED_FOR"]);
            //LogHelper.printInfoLog("REMOTE_ADDR info:" + rq.ServerVariables["REMOTE_ADDR"]);
            var xff = rq.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (xff!=null)
            {
                //LogHelper.printInfoLog("HTTP_X_FORWARDED_FOR info:" + xff.ToString());
                var ips = xff.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (ips!=null)
                {
                    myip = ips[0];
                }
            }
            return myip;
        }
        /// <summary>
        /// 获取客户端地址（原始地址-访问地址）
        /// </summary>
        /// <param name="rq"></param>
        /// <returns></returns>
        public static string GetClientIP(HttpRequestBase rq)
        {
            string clientIP = GetXFFAddress(rq);
            if (string.IsNullOrEmpty(clientIP))
            {
                clientIP = GetUserHostAddress(rq);
            }
            //LogHelper.printInfoLog("Get Client IP:" + clientIP);
            return clientIP;
        }
    }
}
